﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using Silvermoon.Classes;

namespace Silvermoon.Controls
{
    public class DatePicker : TextBox
    {
        private string format = CultureInfo.CurrentUICulture.DateTimeFormat.LongDatePattern;

        private DateTime date = DateTime.Now;

        public DatePicker()
            : base()
        {
            StyleName = "DatePicker";
            AllowPress = true;
            OnDateChanged();
        }

        /// <summary>
        /// Gets or sets the format pattern which converts the date to string.
        /// </summary>
        public string Format
        {
            get { return format; }
            set
            {
                if (format != value)
                {
                    format = value;
                    OnDateChanged();
                }
            }
        }

        public DatePickerMode Mode { get; set; }

        public override bool ReadOnly
        {
            get { return true; }
            set { }
        }


        public DateTime Date
        {
            get { return date; }
            set
            {
                if (date != value)
                {
                    date = value;
                    OnDateChanged();
                }
            }
        }

        protected virtual void OnDateChanged()
        {
            Text = date.IsEmpty() ? "" : date.ToString(format);
        }

        protected internal override void OnTap(TapEventArgs e)
        {
            base.OnTap(e);
            if (!e.Handled)
            {
                DatePickerDialog dlg = new DatePickerDialog { Date = this.Date, Mode = this.Mode };
                dlg.Selected += new EventHandler<DateEventArgs>(OnDateSelected);
                dlg.Shown += new EventHandler(OnDialogShown);
                dlg.Hiding += new EventHandler(OnDialogHiding);
                dlg.Show();
            }
        }

        protected override void CheckInputControl()
        {
            Window w = Window;
            if (w != null) w.IsKeyboardVisible = false;
        }

        void OnDialogHiding(object sender, EventArgs e)
        {
            Window w = Window;
            if (w != null) w.Visible = true;
        }

        void OnDialogShown(object sender, EventArgs e)
        {
            Window w = Window;
            if (w != null) w.Visible = false;
        }

        void OnDateSelected(object sender, DateEventArgs e)
        {
            Date = e.Date;
        }
    }
}
